﻿using SimplePersonManager.DataAccess;
using SimplePersonManager.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimplePersonManager
{
    public class SimplePersonManager
    {
        IRepository _repository;
        
        public SimplePersonManager(IRepository repository)
        {
            _repository = repository;
        }

        public SimplePersonManager()
            : this(new AzureTableStorageRepository())
        {
        }

        public IEnumerable<Person> GetPeople()
        {
            return _repository.RetrieveAll();
        }

        public Person GetPersonByName(string name)
        {
            if (String.IsNullOrEmpty(name))
                throw new ArgumentException("Person name cannot be empty", "name");

            var person = _repository.RetrievePerson(name);
            return person;
        }

        public void SavePerson(Person person)
        {
            if (person == null)
                throw new ArgumentNullException("person");

            if (String.IsNullOrEmpty(person.Name))
                throw new ArgumentException("Person name cannot be empty");

            var personAlreadyStored = GetPersonByName(person.Name);
            if (personAlreadyStored != null)
                throw new DuplicatePersonException();

            _repository.StorePerson(person);
        }        
    }
}
